#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>

#include "logger.h"


/* 返回温度采样  */
int get_temp( float *temp)
{
	char             buf[128];
        int              fd=-1;
        char            *p;
        DIR             *dir;	
	char             w1[128]="/sys/bus/w1/devices/";
	struct dirent   *rnext;
	char            *tmp;
	char             cbuf[32];
	char             slave[32]="/w1_slave";
	dir=opendir(w1);


	if( !temp )
	{
		log_error("ERROR: Invalid input arguments\n");//无效的参数
		return -1;
	}

        if(!dir)
	{	
		log_error("open file filure : %s\n", strerror(errno));
		return -1;
	}

	while (NULL!=(rnext=readdir(dir)))//readdir返回目录流下的下一个目录进入点
	{
	      //  printf("%s\n", rnext->d_name);
                if(strstr(rnext->d_name,"28-"))
	        {
		      strncpy(cbuf, rnext->d_name, sizeof(cbuf));
                }
	}	
        closedir(dir);
	strncat(w1, cbuf, sizeof(w1)-strlen(w1));//将cbuf的字符追加到W1后
	strncat(w1, slave, sizeof(w1)-strlen(w1));

	if((fd=open(w1, O_RDONLY)) < 0)
	{
	    	log_error("open file filure: %s\n", strerror(errno));

	}
	memset(buf, 0, sizeof(buf));
        read(fd, buf, sizeof(buf));
	p=strstr(buf, "t=")+2;

	if( !p )
	{
		log_error("can not find it\n");
	}

	*temp = atof(p)/1000;//把p字符串转换为浮点数
    close(fd);
    return 0;
 }


/* 将穿过来的地址赋值时间*/
void get_time( char *ptr)
{
	time_t  current_time;
	struct tm *current;//定义tm结构体指针
	char time_data[32];

	time(&current_time);//获取从1970年到现在的秒数
	
	current = localtime(&current_time);//将秒数转换为日期	
	//时间转换,初始化结构体数组
	memset (time_data, 0, sizeof(time_data));
	sprintf(time_data,"%04d-%02d-%02d  %02d:%02d:%02d",current->tm_year+1900,current->tm_mon+1,current->tm_mday,current->tm_hour,current->tm_min,current->tm_sec);//将日期存放到time_data中
//	printf("Current time is:%s", time_data);
	strncpy(ptr, time_data, sizeof(time_data));
   
    return ;
}
